<?php

namespace app\admin\controller;

use app\admin\model\SupervisionUsers;
use think\Db;
use think\Request;

use app\admin\model\Image;
use app\admin\model\User;

/**
 * 信访件
 */
class Letter extends Base
{

    public function __construct() {
        parent::__construct();

        $this->model = 'letter';
        $this->addView = 'letter:add';
        $this->indexView = 'letter:list';
        $this->editView = 'letter:edit';

        $defaultWhere['status'] = ['neq', 2];
        $this->defaultWhere = $defaultWhere;

        $this->redirect = 'admin/letter/index';
        $this->searchFields = [
            'title' => [
                'label'     => '标题',
                'field'     => 'title',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'
            ],
            'isPass' => [
                'field'     => 'isPass',
                'type'      => 'select',
                'disabled'  => false,
                'data' => [
                    '' => '全部',
                    '1' => '等待处理',
                    '3' => '进展中',
                    '4' => '已完成',
                ]
            ],
        ];
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);

            if(isset($filter['title']) && $filter['title']){
                $where['title'] = ['like', '%'.$filter['title'].'%'];
            }
            if(isset($filter['isPass']) && $filter['isPass']){
                $where['status'] = $filter['isPass'];
            }
        }

        return $where;
    }

    /**
     * 列表
     */
    public function index() {
        $request = $this->request;
        $param = $request->param();
        // Reset filter

        if ($request->param('reset')) {
            return redirect(fullUrl($request->path()));
        }

        if($request->isAjax()){
            $model = model($this->model);
            // 每页起始条数
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];
            // 排序条件
            $columns = $param['order'][0]['column'];
            $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                //$model = $model->where($this->defaultWhere);
                $where = array_merge($this->defaultWhere, $where);
            }

            $list = $model->where($where)
                //->whereOr('status','neq',2)
                ->limit($start, $length)
                ->order($order)
                ->select();
            foreach($list as $v)
            {
                if ($v['reply'] == 1){
                    $v['reply'] = '满意';
                }
                if ($v['reply'] == 2){
                    $v['reply'] = '基本满意';
                }
                if ($v['reply'] == 3){
                    $v['reply'] = '不满意';
                }
                if ($v['reply'] == ''){
                    $v['reply'] = '--';
                }
                if ($v['status'] == 1){
                    $v['status'] = '待处理';
                }
                if ($v['status'] == 3){
                    $v['status'] = '处理中';
                }
                if ($v['status'] == 4){
                    $v['status'] = '已完成';
                }
                $model = model('image');
                $v['files'] = $model->where(['relatedId'=>$v['id']])->count();
            }
            $count = count($list);
            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $list,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];
            return json($result);
        }

        return self::show($this->indexView, [
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param()
        ]);
    }

    /**
     * Show
     *
     * @param $template
     * @param array $data
     * @return mixed
     */
    private function show($template, $data = []) {

        return $this->view->fetch($template, $data);
    }

    public function edit(Request $request) {
        $id = $request->param('id');
        $model = model($this->model);
        $where['id'] = $id;
        $info = $model->where($where)->find();
        $this->assign('info',$info);
        $Image = \app\admin\model\Image::where('relatedId',$info['id'])->select();

        if($Image){
            $this->assign('imgfiles',$Image);
        }else{
            $this->assign('imgfiles',null);
        }
        $info['name'] = User::where(['id'=>$info['user_id']])->field('p_name,id as userId')->find();

        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }

        return $this->view->fetch('edit', [
            'info' => $info,
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param(),
            'pathtype' => 'edit'
        ]);
    }

    /**
     * 修改
     */
    public function editPost(Request $request, $redirect = '') {
        $model = model($this->model);

        //save data
        if ($request->isPost()) {
            $data = $request->param();
            // Update data
            $data['updateDate'] = date('Y-m-d H:i:s',time());

            $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

            if($result !== false) {
                if (isset($data['enclosure']) && !empty($data['enclosure'])) {
                    $this->editFiles($data['imgIds'],$data['id']);
                }

                if ($result) {
                    return $this->success('编辑成功！', 'admin/' . strtolower($this->model) . '/index');
                } else {
                    return $this->success('编辑成功！', $redirect);
                }
            } else {
                return $this->error($model->getError());
            }
        } else {
            return $this->error('error !');
        }
    }

    /**
     * 删除
     */
    public function delete(Request $request)
    {
        $id = $request->param('id');
        $model = model($this->model);
        $data = [
            'status' => 2
        ];
        $where = [
            'id' => $id
        ];
        $resule = $model->update($data,$where,true);
        if($resule){
            return $this->success('删除成功',$this->redirect);
        }else{
            return $this->error('error !');
        }
    }

    /**
     * 详情
     */
    public function detail(Request $request) {

        $model = model($this->model);
        $id = $request->param('id');
        $where = [
            'a.id' => $id
        ];
        $fields = 'a.title, a.content,a.status as letterstatus, a.u_content, a.reply, m.*';
        $info = $model->alias('a')
            ->where($where)
            ->join('user m','a.user_id = m.id')
            ->field($fields)
            ->find();

        if ($info['sex'] == 1){
            $info['sex'] = '男';
        }else{
            $info['sex'] = '女';
        }
        $info['location'] = $info['province'].'-'.$info['city'].'-'.$info['county'].'-'.$info['address'];
        $files = Image::where('relatedId',$id)->select();
        if($files){
            $info['files'] = $files;
        }else{
            $info['files'] = NULL;
        }
        if(!$info){
            return $this->error('error !', url($this->redirect));
        }

        $this->assign('info',$info);
        return view();
    }

    /**
     * 修改信访用户
     */
    public function addjoinletter(Request $request)
    {
        $ids = $request->param('ids');
        $model = model('user');
        $ruslet = $model->where(['id'=>$ids])->find();
        return json(['code' => 1, 'msg' => '添加成功！', 'data' => $ruslet]);
    }

    /**
     * 修改图片
     */
    private function editFiles($imgIds,$relatedId){
        if(!is_array($imgIds)){
            $res = [];
            $res[0] = $imgIds;
            $imgIds = $res;
        }
        $ImageList =  \app\admin\model\Image::where('relatedId',$relatedId)->field('id')->select();
        if($ImageList){
            $alreadylist = [];
            foreach ($ImageList as $v){
                array_push($alreadylist,$v['id']);
            }
            $reslist = array_diff($imgIds,$alreadylist);
            $list = [];
            if($reslist){
                foreach ($reslist as $v){
                    array_push($list,['id'=>$v,'relatedId'=>$relatedId]);
                }
            }
        }else{
            $list = [];
            foreach ($imgIds as $v){
                array_push($list,['id'=>$v,'relatedId'=>$relatedId]);
            }
        }
        if($list){
            $Image = new \app\admin\model\Image();
            $Image->isUpdate()->saveAll($list);
        }
    }

    /**
     * 删除单张图片
     */
    public function imgDel(Request $request)
    {
        $param = $request->param();
        $id = $param['id'];
        if($id != NULL){
            Db::table('image')->where('id',$id)->delete();  //删除总表记录
            //Db::table('image')->where('imgUrl', $url)->delete();  //删除总表记录
            return json(['message'=>'success','code'=>'1']);
        }else{
            return json(['message'=>'删除失败','code'=>'2']);
        }
    }
}
